export function readStorage(): TodoListData {
  const readData = localStorage.getItem("todoList");
  if (readData === null) {
    console.log("localStorage中不存在已存储的数据，正在初始化");
    const list = new Array<ITodo>();
    localStorage.setItem("todoList", JSON.stringify(list));
    console.log("初始化成功");
    return list;
  } else {
    console.log("localStorage已有数据，正在读取");
    const res = JSON.parse(readData);
    console.log("读取成功", res);
    return res;
  }
}

export function writeStorage(data: TodoListData): void {
  localStorage.setItem("todoList", JSON.stringify(data));
  console.log("写入数据成功", data);
}

const compareByTime = (a: ITodo, b: ITodo): number => {
    if (a.ctime > b.ctime) return -1;
    return 1;
};

export function todoListSort(data: TodoListData): TodoListData {
  const unfinished = new Array<ITodo>();
  const finished = new Array<ITodo>();
  for (const item of data) {
    if (item.finished) {
      finished.push(item);
    } else {
      unfinished.push(item);
    }
  }
  return unfinished.sort(compareByTime).concat(finished.sort(compareByTime));
}
